<template>
  <div class="app-container customer-div">
    <div style="margin-top: 40px">
      <!--搜索-->
      <el-form :inline="true" :model="listQuery" size="mini" label-width="100px">
        <el-form-item label="发货单号：">
          <el-input v-model="listQuery.deliverSn"></el-input>
        </el-form-item>
        <el-form-item label="发货日期：">
          <el-date-picker
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="listQuery.deliverDate"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="合同号：">
          <el-input v-model="listQuery.orderSn"></el-input>
        </el-form-item>
        <el-form-item label="客户名称：">
          <el-autocomplete
                  clearable
                  class="inline-input"
                  value-key="customerName"
                  :fetch-suggestions="querySearch"
                  v-model="listQuery.keywords"
                  placeholder="请输入内容"
                  @select="handleSelectCustomerName"
                  :trigger-on-focus="false"
                  style="width: 270px;"
          ></el-autocomplete>
        </el-form-item>
        <el-form-item label="业务员：">
          <el-select v-model="listQuery.userId" filterable placeholder="请选择" clearable>
            <el-option
                    v-for="item in userOptionList"
                    :key="item.userId"
                    :label="item.userName"
                    :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收货状态：">
          <el-select v-model="listQuery.isReceipt" class="input-width" style="width:195px" placeholder="请选择" clearable>
            <el-option :value="0" label="未收货" :key="0"></el-option>
            <el-option :value="1" label="已收货" :key="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开票日期：">
          <el-date-picker
                  :default-time="['00:00:00', '23:59:59']"
                  v-model="listQuery.invoiceTime"
                  type="daterange"
                  format="yyyy 年 MM 月 dd 日"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="开票状态：">
          <el-select v-model="listQuery.invoiceState" class="input-width" style="width:195px" placeholder="请选择" clearable>
            <el-option :value="1" label="已开票" :key="1"></el-option>
            <el-option :value="0" label="未开票" :key="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="发票号：">
          <el-input v-model="listQuery.invoiceNo"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="handleSearchList()"
            type="primary">
            查询
          </el-button>
          <el-button
                  v-if="invoiceListExport"
                  @click="downloadExcel()"
                  type="primary">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="margin-top:20px">
      <el-radio-group v-model="listQuery.orderBy" size="small" @change="handleSearchList">
        <el-radio-button label="default">默认排序</el-radio-button>
        <el-radio-button label="custoer">按公司排序</el-radio-button>
      </el-radio-group>
    </div>
      <!--数据列表-->
      <div class="table-container">
        <el-table
          v-loading="listLoading"
          :data="tableData"
          border
          style="width: 100%; margin-top: 20px">
          <el-table-column  label="发货单号" width="140" align="center" prop="orderSn">
            <template slot-scope="scope">
              <div @click="toDeliverCon(scope.row)" style="color:#409EFF;cursor: pointer;vertical-align: middle">
                {{scope.row.deliverSn}}
              </div>
            </template>
          </el-table-column>
          <el-table-column  label="订单号" width="140" align="center" prop="orderSn">
            <template slot-scope="scope">
              <el-link @click="toOrderDetail(scope.row.orderId)" type="primary" style="font-size:12px">
                {{scope.row.orderSn}}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            label="客户名称"
            width="300">
            <template slot-scope="scope">
                {{scope.row.customerName}}
            </template>
          </el-table-column>
          <el-table-column
                  label="发货日期"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.shipTime}}
            </template>
          </el-table-column>
          <el-table-column
            prop="orderCompanyName"
            align="center"
            label="合同公司"
            width="100">
          </el-table-column>
          <el-table-column
            class-name="cspantd"
            align="center"
            width="250"
            label="产品名称">
            <template slot-scope="scope">
              <div class="tdDiv" v-for="(item,index) in scope.row.list" :style="{'border-bottom': index==scope.row.list.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5',}">
                {{item.goodsName}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            class-name="cspantd"
            label="订单数量"
            width="100"
            align="center">
            <template slot-scope="scope">
              <div class="tdDiv" v-for="(item,index) in scope.row.list" :style="{'border-bottom': index==scope.row.list.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5',}">
                {{item.goodsNum}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
                  class-name="cspantd"
                  label="订单单价"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              <div class="tdDiv" v-for="(item,index) in scope.row.list" :style="{'border-bottom': index==scope.row.list.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5',}">
                {{item.goodsPrice}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            class-name="cspantd"
            label="订单金额"
            width="120"
            align="center">
            <template slot-scope="scope">
              <div class="tdDiv" v-for="(item,index) in scope.row.list" :style="{'border-bottom': index==scope.row.list.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5',}">
                {{item.goodsAmount}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
                  class-name="cspantd"
                  label="发货数量"
                  width="120"
                  align="center">
            <template slot-scope="scope">
              <div class="tdDiv" v-for="(item,index) in scope.row.list" :style="{'border-bottom': index==scope.row.list.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5',}">
                {{item.shipGoodsNum}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
                  class-name="cspantd"
                  label="发货金额"
                  width="120"
                  align="center">
            <template slot-scope="scope">
              <div class="tdDiv" v-for="(item,index) in scope.row.list" :style="{'border-bottom': index==scope.row.list.length-1 ? '0px solid #EBEEF5' : '1px solid #EBEEF5',}">
                {{item.shipGoodsAmount}}
              </div>
            </template>
          </el-table-column>
          <el-table-column
                  label="业务员"
                  width="100"
                  align="center">
            <template slot-scope="scope">
              {{scope.row.userName }}
            </template>
          </el-table-column>
          <el-table-column
                  label="收货地址"
                  width="400">
            <template slot-scope="scope">
              {{scope.row.addressInfo}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="送货类型"
                  width="150">
            <template slot-scope="scope">
              {{scope.row.indexSendType}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="收货状态"
                  width="100">
            <template slot-scope="scope">
                {{scope.row.goodsReceipt ? '已收货' : '未收货'}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="是否开票"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.invoiceState == 1 ? '是':'否'}}
            </template>
          </el-table-column>
          <el-table-column
                  align="center"
                  label="开票时间"
                  width="100">
            <template slot-scope="scope">
              {{scope.row.invoiceTime}}
            </template>
          </el-table-column>

          <el-table-column
                  align="center"
                  label="操作人"
                  width="150">
            <template slot-scope="scope">
              {{scope.row.invoiceUserName}}
            </template>
          </el-table-column>
          <el-table-column
                  fixed="right"
                  align="center"
                  label="发票号"
                  width="150">
            <template slot-scope="scope">
              {{scope.row.invoiceNo}}
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            width="80"
            label="操作"
            align="center">
            <template slot-scope="scope">
              <el-button
                  v-if="scope.row.invoiceState == 0"
                  type="text"
                  size="mini"
                  @click="showDialog(scope.row)">确认开票
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10,15,20]"
        :total="count">
      </el-pagination>
    </div>

    <!--确认开票-->
    <el-dialog
            :close-on-click-modal="false"
            :beforeClose="handleClose"
            title="确认开票"
            :visible.sync="dialogVisible"
            width="300px">
      <div style="font-size:12px;line-height: 40px">请核对开票金额</div>
      <el-form :model="priceForm" size="mini" label-width="90px"  ref="priceForm">
          <el-form-item label="发货单号：" style="margin-bottom:0">
              {{priceForm.deliverSn}}
          </el-form-item>
          <el-form-item label="公司名称：" style="margin-bottom:0">
            {{priceForm.customerName}}
          </el-form-item>
        <el-form-item label="发货数量：" style="margin-bottom:0">
          {{priceForm.shipGoodsNum}}
        </el-form-item>
        <el-form-item label="发货金额：" style="margin-bottom:0;">
          {{priceForm.shipGoodsAmount}}
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确认开票</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import {getCustomerOption,getOrderUsersList,postOrderPay,invoicesList,invoicesEnter} from '@/api/partner'
  import {validateCommission} from '@/utils/validate';
    import {formatDate} from '@/utils/date';
    import store from '@/store'
    import { mapGetters } from 'vuex'
    const defaultListQuery={
      "deliverSn"    :    "", //发货单号
      "orderSn"    :      "",   //订单号
      "userId"     :      null,  //业务员Id
      "deliverDate" :     null, //发货时间
      "customerName" :    "", //客户名称
      "pageNum"      :    1,  //第几页
      "pageSize"     :    10, //每页几条
      "invoiceState":null,
      "invoiceTime" : null,
      "orderBy":"default",
      isReceipt:null,
      invoiceNo:'',
    };
    const defaultPriceForm={
      deliverId:'',
      deliverSn : '',
      customerName:'',
      shipGoodsNum:'',
      shipGoodsAmount:'',
    };
    export default {
      name: "index",
      data(){
        const validatePayAmount = (rule, value, callback) => {
          if (!validateCommission(parseFloat(value))) {
            callback(new Error('非负整数或小数'))
          } else if(value > this.priceForm.unPaidAmount){
            callback(new Error('收款金额大于未付金额'))
          }else {
            callback()
          }
        };
          return {
              listQuery: JSON.parse(JSON.stringify(defaultListQuery)),
              tableData: [],
              count: 0,
              listLoading: false,
              userOptionList:[],
              roles:store.getters.roles ? store.getters.roles : [],
              dialogVisible:false,
              priceForm:JSON.parse(JSON.stringify(defaultPriceForm)),
              btnLoading : false,
              upUrl:'',
              statisticsCount:0,
              statisticsAmount:0,
              statisticsGoodsNum:0,
          }
      },
      computed: {
        ...mapGetters([
          'name',
          'mobile',
          'userId'
        ]),
        isCanCustomerByAll(){
          if(this.roles.indexOf("customerByAll") != -1){
            return true
          }else{
            return false
          }
        },
        invoiceListExport(){
          if(this.roles.indexOf("invoiceListExport") != -1){
            return true
          }else{
            return false
          }
        },
      },
      created() {
        let time = new Date();
        let day = time - time % (24 * 60 * 60 * 1000) - 8 * 60 * 60 * 1000;
        let end = new Date(day + 24 * 60 * 60 * 1000-1000);
        let start = new Date(day - 7*24 * 60 * 60 * 1000);
        let endDate = formatDate(end, 'yyyy-MM-dd hh:mm:ss');
        let startDate = formatDate(start, 'yyyy-MM-dd hh:mm:ss');
        this.listQuery.createDate = [startDate,endDate];
        if (localStorage.getItem('accountingListQuery')){
          this.listQuery = JSON.parse(localStorage.getItem('accountingListQuery'));
          localStorage.removeItem('accountingListQuery');
        }

        this.getList();
        this.getUserOptionList();
      },
      watch:{

      },
      filters: {
        formatCreateTime(time) {
          if(time){
            let date = new Date(time);
            return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
          }else{
            return '--'
          }
        },
      },
      methods:{
          toOrderDetail(orderId){
              let routeData = this.$router.resolve({name:'purchaseDetail',query:{id:orderId,type:'see',seeType:'caiWu'}});
              window.open(routeData.href);
          },
        //查看发货单
        toDeliverCon(item){
          let routeData = this.$router.resolve({name:'deliverCon',query:{id:item.deliverId,type:'see'}});
          window.open(routeData.href);
        },
        //下载excle
        downloadExcel(){
          let params = JSON.parse(JSON.stringify(this.listQuery));
          params.export = 1;
          invoicesList(params).then((res)=>{
            require.ensure([], () => {
              const { export_json_to_excel } = require('sheet/Export2Excel');
              const tHeader = res.title;
              const filterVal = res.columns;
              const list = res.list;
              const data = this.formatJson(filterVal, list);
              export_json_to_excel(tHeader, data, res.fileName);
            })
          })
        },

        //下载表格数据格式化
        formatJson(filterVal, jsonData) {
          return jsonData.map(v => filterVal.map(j => v[j]))
        },
        //显示确认开票弹窗
        showDialog(item){
            this.dialogVisible = true;
            this.priceForm = JSON.parse(JSON.stringify(defaultPriceForm));
            this.priceForm.deliverId = item.deliverId;
            this.priceForm.deliverSn = item.deliverSn;
            this.priceForm.customerName = item.customerName;
            this.priceForm.shipGoodsNum = item.shipGoodsNum;
            this.priceForm.shipGoodsAmount = item.shipGoodsAmount;
        },

        //关闭确认开票弹窗
        handleClose(){
          this.dialogVisible = false;
          // this.$refs.priceForm.clearValidate();
        },

        //提交确认开票
        handleConfirm(){
          this.$refs['priceForm'].validate((valid) => {
            if (valid) {
              this.btnLoading = true;
              let pa = {};
              pa.deliverId = this.priceForm.deliverId;
              invoicesEnter(pa).then(()=>{
                this.btnLoading = false;
                this.dialogVisible = false;
                this.getList()
              }).catch(()=>{
                this.btnLoading = false;
              })
            }
          })
        },

          //获取员工下拉选项
          getUserOptionList(){
            getOrderUsersList().then((res)=>{
                  this.userOptionList = res;
              })
          },

          //选择员工名称
          handleSelectUserName(key,item){
              this.listQuery[key] = item.userId;
          },

          //客户名称输入匹配
          querySearch(queryString, cb){
              getCustomerOption({keywords:queryString}).then((res)=>{
                  cb(res);
              })
          },

          //选择客户名称
          handleSelectCustomerName(item){
              this.listQuery.keywords = item.customerName
          },

        /**
         * 切换选择状态
         */
        handleSelect(key, keyPath){
            this.listQuery = JSON.parse(JSON.stringify(defaultListQuery)),
            this.listQuery.tab = key;
            if(key=='all'){
              this.listQuery.payState = null
            }else if(key=='unPay'){
              this.listQuery.payState = 1;
            }
            this.handleSearchList();
        },
        handleSizeChange(val){
          this.listQuery.pageNum = 1;
          this.listQuery.pageSize = val;
          this.getList();
        },
        handleCurrentChange(val){
          this.listQuery.pageNum = val;
          this.getList();
        },

        handleSearchList(){
          this.listQuery.pageNum = 1;
          this.getList();
        },

        //获取发票列表
        getList() {
          this.listLoading = true;
          invoicesList(this.listQuery).then(response => {
            this.tableData = response.list;
            this.count = response.count;
            this.statisticsAmount = response.statisticsAmount;
            this.statisticsCount = response.statisticsCount;
            this.statisticsGoodsNum = response.statisticsGoodsNum;
            this.listLoading = false;
          }).catch(()=>{
            this.listLoading = false;
          });
        },

        //去收款单页
        toReceiptList(item){
          localStorage.setItem('accountingListQuery', JSON.stringify(this.listQuery));
          this.$router.push({name:'receiptList',query:{orderSn:item.orderSn}})
        },
      },
    }
</script>

<style lang="scss">
  .cspantd .cell{
    padding:0
  }
</style>
